package com.springbootbase.springbootproject.controller;

import com.springbootbase.springbootproject.pojo.Result;
import com.springbootbase.springbootproject.pojo.User;
import com.springbootbase.springbootproject.service.UserService;
import com.springbootbase.springbootproject.utils.JwtUtil;
import com.springbootbase.springbootproject.utils.Md5Util;
import com.springbootbase.springbootproject.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\s{5,16}$") String username,@Pattern(regexp = "^\\s{5,16}$") String password,String userType){
        User u = userService.findByUserName(username, userType);
        if (u==null){
            userService.register(username,password,userType);
            return Result.success();
        }else {
            return Result.error("用户名已被占用");
        }
    }

    @GetMapping("/getInfo")
    public Result getInfo(String username,String userType){
        User u = userService.findByUserName(username,userType);
        return Result.success(u);
    }

    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") String username , @Pattern(regexp = "^\\S{5,16}$") String password, String userType){
        User u = userService.findByUserName(username,userType);
        if (u==null){
            return Result.error("该用户名未注册");
        }else {
            if (Md5Util.getMD5String(password).equals(u.getPassword())) {
                Map<String, Object> claims = new HashMap<>();
                claims.put("userType",u.getUserType());
                claims.put("username",u.getUsername());
                claims.put("id",u.getId());
                String token = JwtUtil.genToken(claims);
                return Result.success(token);
            }else{
                return Result.error("密码输入错误");
            }
        }
    }


    //@RequestBody 注解用于获取请求体中的数据，@Validated 注解用于验证数据是否符合规则。
    @PostMapping("/update")
    public Result update(Long id,String username,String email,String phone){
        userService.update(id,username,email,phone);
        return Result.success();
    }


}
